<?php
/**
 * Custom auth storage implementation to handle cookies
 *
 * @author	Iain Edminster
 */
class Bliss_User_Storage_Cookie implements Zend_Auth_Storage_Interface
{
	/**
	 * Cookie namespace
	 *
	 * @var	string
	 */
	protected $_namespace;

	/**
	 * Cookie expire time in seconds
	 *
	 * @var	int
	 */
	protected $_cookieExpire;

	/**
	 * Cookie path
	 *
	 * @var	string
	 */
	protected $_cookiePath;

	/**
	 * Cookie domain
	 *
	 * @var	string
	 */
	protected $_cookieDomain;

	/**
	 * Initialized the storage and sets the namespace
	 *
	 * @param string $namesace Cookie namespace
	 * @param int $expire Lifetime of the cookie in seconds
	 * @param string $path Cookie path
	 * @param string $domain Cookie domain
	 */
	public function __construct($namespace=null, $expire=null, $path=null, $domain=null) {
		$this->_namespace	= isset($namespace) ? $namespace : 'Bliss_User_Cookie';

		$this->_cookieExpire	= $expire;
		$this->_cookiePath		= $path;
		$this->_cookieDomain	= $domain;
	}

	/**
     * Returns true if and only if storage is empty
     *
     * @throws Zend_Auth_Storage_Exception If it is impossible to determine whether storage is empty
     * @return boolean
     */
    public function isEmpty() {
		return !isset($_COOKIE[$this->_namespace]);
	}

    /**
     * Returns the contents of storage
     *
     * Behavior is undefined when storage is empty.
     *
     * @throws Zend_Auth_Storage_Exception If reading contents from storage is impossible
     * @return mixed
     */
    public function read() {
		return $_COOKIE[$this->_namespace];
	}

    /**
     * Writes $contents to storage
     *
     * @param  mixed $contents
     * @throws Zend_Auth_Storage_Exception If writing $contents to storage is impossible
     * @return void
     */
    public function write($contents) {
		$expire	= isset($this->_cookieExpire) ? time()+$this->_cookieExpire : null;
		$path	= isset($this->_cookiePath) ? $this->_cookiePath : null;
		$domain	= isset($this->_cookieDomain) ? $this->_cookieDomain : null;

		setcookie($this->_namespace, $contents, $expire, $path, $domain);
	}

    /**
     * Clears contents from storage
     *
     * @throws Zend_Auth_Storage_Exception If clearing contents from storage is impossible
     * @return void
     */
    public function clear() {
		$path	= isset($this->_cookiePath) ? $this->_cookiePath : null;
		$domain	= isset($this->_cookieDomain) ? $this->_cookieDomain : null;

		setcookie($this->_namespace, null, time()-5, $path, $domain);
	}
}
?>